#!/bin/sh
#
#-----------------------------------------------------------------------
# Compile a small C program containing a sequence of assembler
# instructions into an executable that does not need a dynamic linker.
# Very handy for debugging new insns or small snippets without going
# through the multi-pass process of figuring out which SB contains the
# code we're interested in.
#
# Here is a template:
#
#    int main(void)
#    {
#      //FIXME: insert test code here:
#      asm volatile ("lghi %r1,1");    // __NR_exit
#      asm volatile ("lghi %r2,0");    // return code = 0
#      asm volatile ("svc 0");
#      return 0;                       // shuts up GCC
#    }
#
# When running the executable created by this script under valgrind
# there will be only a single super block! Which is exactly what we want
# for debugging.
#
# objdump -d:
#
# 00000000010000b0 <_start>:
# 10000b0:	b3 c1 00 0b       	ldgr	%f0,%r11
# 10000b4:	b9 04 00 bf       	lgr	%r11,%r15
# 10000b8:	a7 19 00 01       	lghi	%r1,1       <---
# 10000bc:	a7 29 00 09       	lghi	%r2,9       <---
# 10000c0:	0a 00             	svc	0           <---
# 10000c2:	a7 18 00 00       	lhi	%r1,0
# 10000c6:	b9 14 00 11       	lgfr	%r1,%r1
# 10000ca:	b9 04 00 21       	lgr	%r2,%r1
# 10000ce:	b3 cd 00 b0       	lgdr	%r11,%f0
# 10000d2:	07 fe             	br	%r14
# 10000d4:	07 07             	nopr	%r7
# 10000d6:	07 07             	nopr	%r7
#
# There are only 2 extra insns ahead of our asm code sequence.
# Everything after the svc insn is not reachable.
#-----------------------------------------------------------------------
#

if [ "x$1" = "x" ]; then
  echo "Usage:  s390-runone  C-file" 1>&2
  echo "   or:  s390-runone  -t"     1>&2
  exit 1
fi

if [ "x$1" = "x-t" ]; then
  echo 'int main(void)'
  echo '{'
  echo '  //FIXME: insert test code here:'
  echo '  asm volatile ("lghi %r1,1");    // __NR_exit'
  echo '  asm volatile ("lghi %r2,0");    // return code = 0'
  echo '  asm volatile ("svc 0");'
  echo '  return 0;                       // shuts up GCC'
  echo '}'
  exit 0
fi

file="$1"
base=`basename "$file" .c`
asm="$base.s"
exe="$base"

if [ "$base" = "$file" ]; then
  echo "$file is not a C file" 1>&2
  exit 1
fi

# Compile the testprogram to assembler
gcc -S -fno-ident -march=arch14  $file
mv "$asm" "$asm.orig"     # save the result

# Rename main with _start, remove cfi stuff and comment lines
sed 's/main/_start/g' "$asm.orig" | grep -v \.cfi_ | grep -v ^# > "$asm"

# Link to executable
gcc -static -Wl,--build-id=none -nodefaultlibs -nostartfiles "$asm" -o "$exe"

echo "$exe created"
exit 0
